<script setup>
import { downloadAttachment } from '@/api/comprehensive'
import {
  useOpenEcardPage,
  useOpenReservationPage,
  useDirectPaymentHospitals
} from '@/composables/open-link.js'
import ECardModal from '@/components/PersonalInfo/ECardModal.vue'
import HospitalModal from './HostipalInfo.vue'
import WeatchModal from './WechatStatus.vue'
import RemarkModal from '@/components/PersonalInfo/RemarkModal.vue'
import ResponsiblePopover from '@/components/PersonalInfo/ResponsiblePopover.vue'
import YearPopover from '@/components/PersonalInfo/YearPopover.vue'
import { ref, watch, unref, onMounted, computed } from 'vue'
import { queryPolicyInfo } from '@/api/comprehensive'
import { useAccountStore } from '@/stores/account'
import { downloadFile } from '@/utils/file'
import { useRoute } from 'vue-router'
import { message as AMessage } from 'ant-design-vue'
const route = useRoute()

const accountStore = useAccountStore()
const props = defineProps({
  insuredInfo: {
    type: Object,
    required: () => {}
  }
})
const emit = defineEmits(['updatePolicyInfo'])

const isEyeOpen = computed(() => {
  return accountStore.DESENSITIZATION
})
// 脱敏
watch(
  () => isEyeOpen.value,
  (newValue, oldValue) => {
    fetchPolicyInfo('sourceEye')
  }
)
// 切换被保人，重新获取保单信息
watch(
  () => props.insuredInfo.doc_id,
  (id) => {
    fetchPolicyInfo('changeDocId')
  }
)
onMounted(() => {
  fetchPolicyInfo('init')
})
function getPopupContainer(triggerNode) {
  return triggerNode.parentNode
}
function getPopupContainers(triggerNode) {
  return triggerNode.parentNode.parentNode
}
// 入保附件下载
let spinning = ref(false)
async function downloadInsuredFile() {
  if (spinning.value) return
  const params = {
    grpPlanCode: unref(policyInfo).grpPlanCode, // 计划编码
    grpContNo: unref(policyInfo).grpContNo, // 内部保单号
    undId: unref(policyInfo).underwriterId, // 承保商
    insuredId: unref(policyInfo).insuredId // insuredId
  }
  let res = null
  spinning.value = true
  try {
    res = await downloadAttachment(params)
  } catch (err) {
    console.log('err', err)
  } finally {
    spinning.value = false
  }
  if (res) {
    downloadFile(res)
    AMessage.success('下载成功')
  }
}

const policyList = ref([])
const policyInfo = ref({})
const insuredId = ref(route.query.insuredId)

async function fetchPolicyInfo(type) {
  const { doc_id } = unref(props.insuredInfo)
  let res = null
  const data = {
    desensitization: unref(isEyeOpen) ? '02' : '01',
    doc_id
  }
  try {
    res = await queryPolicyInfo(data)
  } catch (err) {
    console.log('err', err)
  }
  if (res?.isSuccess) {
    policyList.value = res?.data || []
    if (type == 'changeDocId') {
      policyInfo.value = unref(policyList)[0] || {}
    }
    if (type == 'init') {
      policyInfo.value =
        unref(policyList).find((policy) => policy.insuredId == unref(insuredId)) || {}
    }
    // 脱敏切换，无需更新policyInfo的信息
    if (type == 'sourceEye') return
    emit('updatePolicyInfo', policyInfo.value)
  }
}
function updateCustomInfoFun(selectYearInfo) {
  policyInfo.value = selectYearInfo
  emit('updatePolicyInfo', selectYearInfo)
}
// ECard modal
const eCardVisible = ref(false)
function openECardModal() {
  eCardVisible.value = true
}
// hospital modal
const hospitalVisible = ref(false)
const weatchVisible = ref(false)
const getPolicyInfoData = (str) => {
  if (!str) return str
  let strArr = str.split(';')
  return strArr.length
}
// 欣服务功能开通状态modal
function openServiceModal() {
  weatchVisible.value = true
}
// remark modal
const remarkVisible = ref(false)

function openRemarkModal(info) {
  remarkVisible.value = true
}
// 直付医院列表查询
function openHospitalListPage() {
  useDirectPaymentHospitals({ ...unref(policyInfo) })
}
</script>
<template>
  <div>
    <div class="policy-info">
      <div class="common-info-header">
        <span class="common-info-header-name">
          {{ $t('home.policy.policyInfo') }}
        </span>
        <YearPopover
          @updateCustomInfo="updateCustomInfoFun"
          :info="policyInfo"
          :policyYearList="policyList"
          :requireGetYearList="false"
          :isEyeOpen="isEyeOpen"
        >
          <div class="policy-year-box cursor-pointer mr-20">
            <span class="policy-year">
              {{ policyInfo.policyYear }}
            </span>
            <svg-icon class="arrow-year-icon" size="14" name="arrow-down" />
          </div>
        </YearPopover>
        <a-input
          class="mr-20"
          :value="policyInfo.planTypeEName"
          placeholder="计划类型"
          disabled
          style="width: 240px"
        />
        <a-input
          class="mr-20"
          :value="`${policyInfo.insuredEffectiveDate} ~ ${policyInfo.insuredExpireDate}`"
          placeholder="有效期"
          disabled
          style="width: 240px"
        />
        <div class="line"></div>
      </div>
      <div class="policy-info-main">
        <div class="policy-left">
          <div class="policy-left-header">
            <span class="title">{{ policyInfo.member_id }}</span>
            <svg-icon size="20" @click="openRemarkModal" class="mr-16 ml-16" name="home-remark" />
            <a-tooltip :getPopupContainer="getPopupContainer">
              <template #title>{{ $t('home.policy.PolicyFiles') }}</template>
              <span>
                <a-spin :spinning="spinning">
                  <svg-icon name="home-download" size="20px" @click.native="downloadInsuredFile" />
                </a-spin>
              </span>
            </a-tooltip>
            <ResponsiblePopover :info="policyInfo">
              <a-tooltip :getPopupContainer="getPopupContainer">
                <template #title>
                  <div>{{ $t('home.policy.ServiceInfo') }}</div>
                </template>
                <svg-icon size="20" class="ml-16" name="home-cantact" />
              </a-tooltip>
            </ResponsiblePopover>
          </div>
          <a-flex wrap="wrap" class="tags" :gap="6">
            <a-tag color="#E8F0F3" v-if="policyInfo.mguTpa" class="mgu">{{
              policyInfo.mguTpa
            }}</a-tag>
            <a-tag color="#F5EBD5" v-if="policyInfo.enrollmentStatus" class="status">{{
              policyInfo.enrollmentStatus
            }}</a-tag>
            <a-tag color="#E8F0F3" v-if="policyInfo.relationship" class="mgu">{{
              policyInfo.relationship
            }}</a-tag>
            <a-tag color="#F5EBD5" v-if="policyInfo.vipFlag" class="status center">
              <span> {{ policyInfo.vipFlag }} </span>
              <a-tooltip v-if="policyInfo.vipNotes" :getPopupContainer="getPopupContainers">
                <template #title>{{ policyInfo.vipNotes }}</template>
                <svg-icon class="icon-tag" name="vip-tip" />
              </a-tooltip>
            </a-tag>
            <a-tag color="#E8F0F3" v-if="policyInfo.holdPremium" class="mgu center">
              <span> {{ policyInfo.holdPremium }} </span>
              <a-tooltip
                v-if="policyInfo.holdPremiumReason"
                :getPopupContainer="getPopupContainers"
              >
                <template #title>{{ policyInfo.holdPremiumReason }}</template>
                <svg-icon class="icon-tag" name="guaqi-tip" />
              </a-tooltip>
            </a-tag>
            <a-tag color="#F5EBD5" v-if="policyInfo.premiumPayType" class="status">{{
              policyInfo.premiumPayType
            }}</a-tag>
          </a-flex>
          <a-descriptions
            class="policy-description"
            :column="3"
            :labelStyle="{ color: '#666' }"
            :contentStyle="{ color: '#333', fontWeight: 700 }"
          >
            <a-descriptions-item :label="$t('home.policy.CompanyName')">{{
              policyInfo.clientShortName || '-'
            }}</a-descriptions-item>
            <a-descriptions-item :label="$t('home.policy.UW')">{{
              policyInfo.underwriterName || '-'
            }}</a-descriptions-item>
            <a-descriptions-item :label="$t('home.policy.SubUW')">
              {{ policyInfo.subUwName || '-' }}
            </a-descriptions-item>
            <a-descriptions-item
              :label="$t('home.policy.ExtPolicyNo')"
              class="policy-number-descriptions"
            >
              <div class="policy-number-box" v-if="getPolicyInfoData(policyInfo.policyNumber) > 1">
                <a-tooltip
                  :getPopupContainer="getPopupContainers"
                  overlayClassName="policy-number-tooltip"
                >
                  <template #title
                    ><div class="policy-number-tooltip">
                      {{ policyInfo.policyNumber }}
                    </div></template
                  >
                  <div class="policy-number">{{ policyInfo.policyNumber }}</div>
                </a-tooltip>
              </div>
              <div v-else class="policy-number">{{ policyInfo.policyNumber || '-' }}</div>
            </a-descriptions-item>
            <a-descriptions-item :label="$t('home.policy.ECard')">
              <span>{{ policyInfo.ecardStatus || '-' }}</span>
              <svg-icon
                class="icon-down"
                name="download-ecard"
                @click="useOpenEcardPage(policyInfo.member_id, policyInfo.insuredId)"
              />
              <svg-icon
                class="icon-edit"
                v-if="$auth('comprehensive:query:eCard:switch')"
                name="edit-ecard"
                @click="openECardModal"
              />
            </a-descriptions-item>
            <a-descriptions-item :label="$t('home.policy.FirstInsDate')">
              {{ policyInfo.firstEnrollmentDate || '-' }}</a-descriptions-item
            >
            <a-descriptions-item :label="$t('home.policy.Category')">{{
              policyInfo.category || '-'
            }}</a-descriptions-item>
            <a-descriptions-item :label="$t('home.policy.Residence')">
              {{ policyInfo.residentCountry || '-' }}</a-descriptions-item
            >
            <a-descriptions-item :label="$t('home.policy.USANetwork')">
              {{ policyInfo.usaNetworkTypeName || '-' }}</a-descriptions-item
            >
            <a-descriptions-item :label="$t('home.policy.USANetworkID')">
              {{ policyInfo.usaNetworkId || '-' }}
            </a-descriptions-item>
            <a-descriptions-item :label="$t('home.policy.MSHServiceStatus')">
              <span class="text-decoration" @click="openServiceModal">
                {{ $t('global.view') }}
              </span>
            </a-descriptions-item>
            <a-descriptions-item :label="$t('home.policy.DBList')">
              <span class="text-decoration" @click="openHospitalListPage">
                {{ $t('global.search') }}
              </span>
            </a-descriptions-item>
          </a-descriptions>
        </div>
        <div class="policy-right">
          <div class="policy-right-message policy-right-common">
            <svg-icon
              size="65"
              class="cursor-pointer"
              name="create-reservation"
              @click="useOpenReservationPage({ ...policyInfo, operation: '01' })"
            />
            <span
              class="cursor-pointer"
              @click="useOpenReservationPage({ ...policyInfo, operation: '01' })"
              >{{ $t('home.policy.CreateAppointment') }}</span
            >
          </div>
          <div class="policy-right-reservation policy-right-common">
            <svg-icon size="65" @click="hospitalVisible = true" name="hospital-info" />
            <span class="cursor-pointer" @click="hospitalVisible = true">
              {{ $t('home.policy.HospitalInfo') }}</span
            >
          </div>
        </div>
      </div>
    </div>
    <HospitalModal
      v-if="hospitalVisible"
      :insuredInfo="insuredInfo"
      :policyInfo="policyInfo"
      @updateVisible="(visible) => (hospitalVisible = visible)"
    ></HospitalModal>
    <WeatchModal
      v-if="weatchVisible"
      :insuredInfo="insuredInfo"
      :policyInfo="policyInfo"
      @updateVisible="(visible) => (weatchVisible = visible)"
    ></WeatchModal>
    <ECardModal
      :eCardInfo="policyInfo"
      v-if="eCardVisible"
      @updateVisible="(visible) => (eCardVisible = visible)"
    ></ECardModal>
    <RemarkModal
      v-if="remarkVisible"
      :insuredInfo="insuredInfo"
      :policyInfo="policyInfo"
      @updateVisible="(visible) => (remarkVisible = visible)"
    ></RemarkModal>
  </div>
</template>
<style lang="scss">
.policy-number-descriptions {
  .ant-descriptions-item-label {
    flex-shrink: 0;
  }
}
.policy-number {
  flex: 1;
  max-width: 350px;
  word-break: break-all;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
@media screen and (max-width: 1800px) {
  .policy-number {
    max-width: 320px;
  }
}

@media screen and (max-width: 1700px) {
  .policy-number {
    max-width: 270px;
  }
}
@media screen and (max-width: 1600px) {
  .policy-number {
    max-width: 220px;
  }
}
.policy-number-tooltip {
  width: 455px;
  word-break: break-all;
  .ant-tooltip-inner {
    width: 467px !important;
  }
}

.policy-info {
  position: relative;
  .ant-descriptions .ant-descriptions-row > td {
    padding-bottom: 15px !important;
  }
  .policy-year-box {
    width: 138px;
    height: 32px;
    display: flex;
    border-radius: 6px;
    background-color: #ffffff;
    border: 1px solid #d9d9d9;
    align-items: center;
    position: relative;
    justify-content: space-between;
    padding: 0 11px;
    .policy-year {
      font-size: 14px;
      color: #333333;
    }
    .arrow-year-icon {
      color: #ccc;
    }
  }
  &-main {
    display: flex;
    margin-top: 24px;
    .policy-left {
      padding: 20px 24px;
      padding-bottom: 5px;
      flex: 1;
      min-width: 920px;
      min-height: 251px;
      background: #ffffff;
      box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.05);
      border-radius: 6px;
      margin-right: 20px;
      &-header {
        display: flex;
        align-items: center;
        position: relative;
        .title {
          font-weight: bold;
          font-size: 20px;
          color: $color-text-primary;
        }
        .mr-16 {
          margin-right: 16px;
        }
        .ml-16 {
          margin-left: 16px;
        }
        .svg-icon {
          cursor: pointer;
        }
      }
      .tags {
        margin-top: 22px;
        position: relative;
        .ant-tag {
          cursor: pointer;
        }
        .mgu {
          color: #4d789c;
        }
        .center {
          display: flex;
          align-items: center;
        }
        .status {
          color: #e39e36;
        }
        .icon-tag {
          font-size: 12px;
          margin-left: 3px;
          path {
            color: #e39e36;
          }
        }
      }
      .policy-description {
        margin-top: 16px;

        .svg-icon {
          margin-left: 6px;
          cursor: pointer;
        }
        .text-decoration {
          text-decoration: underline;
          color: #4d789c;
          cursor: pointer;
        }
        .text-decoration:hover {
          color: #97b7c5;
        }
      }
    }
    .policy-right {
      width: 356px;
      min-width: 340px;
      display: flex;
      flex-direction: column;
      &-common {
        flex: 1;
        display: flex;
        align-items: center;
        padding: 0 30px;
        font-weight: bold;
        font-size: 20px;
        color: $color-text-primary;
        background: #ffffff;
        box-shadow: 0px 0px 6px 0px rgba(0, 58, 84, 0.08);
        border-radius: 10px;
        .svg-icon {
          margin-right: 30px;
        }
      }
      &-message {
        margin-bottom: 15px;
      }
    }
  }
}
</style>
